package org.phalanx.servlet.webmessages;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.phalanx.messenging.PhalanxChatMessage;
import org.phalanx.server.ServerCache.CacheManager;
import org.phalanx.server.social.PhalanxChatRoomManager;
import org.phalanx.server.user.PhalanxUser;

public class ChatRoomContext implements WebMessageable {
	public static final String CHAT_CONTEXT = "chat";
	private PhalanxChatRoomManager chatMgr;
	private CacheManager cacheMgr;
	
	public ChatRoomContext(PhalanxChatRoomManager chatMgr, CacheManager cacheMgr){
		this.chatMgr = chatMgr;
		this.cacheMgr = cacheMgr;
	}
	
	@Override
	public void onContextLoadable(String context, Cookie authCookie,
			HttpServletRequest req, HttpServletResponse resp) {
		if (context.equals(CHAT_CONTEXT)){
			String msgType = req.getParameter("type");
			String chatroom = req.getParameter("chatroom");
			String message = req.getParameter("msg");
			String command = req.getParameter("command");
			PhalanxUser u = (PhalanxUser)cacheMgr.getElement("TokenSessionCache", authCookie.getValue());
			
			if (u != null){
				if (msgType.equals("msg")){
					PhalanxChatMessage pMsg = new PhalanxChatMessage();
					pMsg.setAsChatMsg();
					pMsg.setChatRoom(chatroom);
					pMsg.setMessage(message);
					
					chatMgr.onIncomingChat(u.getId(), pMsg);
				}
				else if (msgType.equals("command")){
					if (command != null){
						if (command.equals(PhalanxChatMessage.JOIN_CHAT)){
							if (!chatMgr.chatRoomExists(chatroom)){
								chatMgr.createChatRoom(chatroom);
							}
							chatMgr.addChatListener(u.getId(), chatroom);
						}
						else if (command.equals(PhalanxChatMessage.PART_CHAT)){
							chatMgr.addChatListener(u.getId(), chatroom);
						}
					}
				}
			}
		}

	}

}
